<?php
namespace app\Home\controller;

//公共控制器
use app\common\controller\Homecontroller;

// 导入Cookie
use think\Cookie;

use think\Db;

class User extends Homecontroller {

    // 构造函数

    public function __construct() {
        // 手动把父类的方法获取过来
        parent::__construct();

        // 在控制器的全局中保留一个全局变量
        // app/common/model/user/User.php
        $this->UserModel = model( 'User.User' );
        $this->ConfigModel = model( 'Config' );
        //地区模型
        $this->RegionModel = model( 'Region' );
        $this->PostModel = model( 'Post.Post' );
        $this->CommentModel = model( 'Post.Comment' );
        $this->CollectModel = model( 'User.Collect' );
        $this->RecordModel = model( 'User.record' );
    }

    public function index() {
        // 获取 url 传来的用户id
        $id = $this->request->param( 'userid', 0 );

        // 通过 id 获取用户的信息
        $UserInfo = $this->UserModel->find( $id );

        $UserInfo[ 'cover' ] = is_file( $UserInfo[ 'cover' ] ) ? $UserInfo[ 'cover' ] : 'assets/home/images/back.jpeg';
        $UserInfo[ 'avatar' ] = is_file( $UserInfo[ 'avatar' ] ) ? $UserInfo[ 'avatar' ] : 'assets/home/images/default.jpeg';

        // 用户的帖子
        $postList = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $id ] )->order( 'createtime', 'desc' )->paginate( 10 );

        // 帖子的数量
        $postCount = count( $postList );

        $commentlist = $this->CommentModel->where( [ 'userid' => $id ] )->order( 'createtime', 'desc' )->paginate( 5 );

        //
        if ( $UserInfo ) {
            $this->assign( [
                'UserInfo' => $UserInfo,
                'commentlist' => $commentlist,
                'postList' => $postList,
                'postCount' => $postCount
            ] );
            return $this->fetch( 'consumer' );
        } else {
            return $this->fetch();
        }

    }

    // 用户设置

    public function user() {
        // 获取当前登录用户信息
        $LoginUser = Cookie::get( 'LoginUser' );

        // 获取用户其他信息
        $UserInfo = $this->UserModel->where( [ 'id' => $LoginUser[ 'id' ] ] )->find();

        // 判断用户是否存在
        if ( !$UserInfo ) {
            $this->error( '没有当前用户，请重新登录！' );
            exit;
        }

        if ( $this->request->isPost() ) {
            $params = $this->request->param();

            // 获取操作类型
            $action = $this->request->param( 'action', '' );

            // 修改个人信息
            if ( $action == 'profile' ) {

                $data = [
                    'id' => $LoginUser[ 'id' ], // 提交表单中没有id
                    'email' => $UserInfo[ 'email' ], // 提交表单 email 不可以修改
                    'sex' => $params[ 'sex' ],
                    'nickname' => $params[ 'nickname' ],
                    'province' => $params[ 'province' ],
                    'city' => $params[ 'city' ],
                    'district' => $params[ 'district' ],
                    'content' => $params[ 'content' ]
                ];

                // 更新数据
                $resultProfile = $this->UserModel->isUpdate()->save( $data );

                // 判断返回值操作
                if ( $resultProfile == false ) {
                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    // 组装更新好的信息存入 cookie 中

                    $res = [
                        'id' => $LoginUser[ 'id' ],
                        'nickname' => $params[ 'nickname' ] ? $params[ 'nickname' ] : $UserInfo[ 'nickname' ],
                        'vip' => $LoginUser[ 'vip' ],
                        'auth' => $LoginUser[ 'auth' ],
                        'avatar' => is_file( $LoginUser[ 'avatar' ] ) ? '/'.$LoginUser[ 'avatar' ] : '/assets/home/images/avatar.jpg',
                        'cover' => is_file( $LoginUser[ 'cover' ] ) ? '/'.$LoginUser[ 'cover' ] : '/assets/home/images/back.jpg'
                    ];

                    // 将数据存入cookie
                    Cookie::set( 'LoginUser', $res );
                    $this->success( '更新个人资料成功！' );
                    exit;
                }
            }

            // 修改密码
            if ( $action == 'password' ) {
                // 获取输入的值
                $nowpass = $this->request->param( 'nowpass', '' );
                $pass = $this->request->param( 'pass', '' );
                $repass = $this->request->param( 'repass', '' );

                // 密码盐
                $salt = $UserInfo[ 'salt' ];

                // 加密当前密码
                $nowpass = md5( $nowpass.$salt );

                // 判断输入的密码是否与数据库相同
                if ( $nowpass != $UserInfo[ 'password' ] ) {
                    $this->error( '你输入的密码有误！' );
                    exit;
                }

                // 给新密码加密
                $passs = md5( $pass.$salt );

                // 判断旧密码是否与新密码相同
                if ( $nowpass == $passs ) {
                    $this->error( '你输入的新密码与原先的密码相同！' );
                    exit;
                }

                // 重新生成密码盐
                $salts = randstr( 10 );

                // 新密码加密
                $pass = md5( $pass.$salts );

                // 组装数据
                $data = [
                    'id' => $LoginUser[ 'id' ],
                    'password' => $pass,
                    'salt' => $salts
                ];

                // 修改数据库数据
                $resultPassword = $this->UserModel->isUpdate()->save( $data );

                // 判断返回结果
                if ( $resultPassword == false ) {
                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    $this->success( '密码修改成功！' );
                    exit;
                }
            }

            // 修改头像
            if ( $action == 'avatar' ) {

                // 图片上传
                $imgURL = upload( 'avatar' );

                if ( $imgURL === false ) {
                    $this->error( '修改头像失败！' );
                    exit;
                }

                // 组装数据
                $data = [
                    'id' => $LoginUser[ 'id' ],
                    'avatar' => 'uploads/'.$imgURL
                ];

                // 修改数据库
                $resultImg = $this->UserModel->isUpdate()->save( $data );

                if ( $resultImg === false ) {

                    // 如果更新失败将上传的图片删除
                    @is_file( $data[ 'avatar' ] ) && @unlink( $data[ 'avatar' ] );

                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    // 修改成功后，删除原来的图片
                    $avatar = ltrim( $LoginUser[ 'avatar' ], '/' );
                    @is_file( $avatar ) && @unlink( $avatar );

                    // 组装cookie的信息
                    $cookie = [
                        'id' => $LoginUser[ 'id' ],
                        'nickname' => $LoginUser[ 'nickname' ],
                        'vip' => $LoginUser[ 'vip' ],
                        'auth' => $LoginUser[ 'auth' ],
                        'avatar' => is_file( $data[ 'avatar' ] ) ? '/'.$data[ 'avatar' ] : '/assets/home/images/avatar.jpg',
                        'cover' => is_file( $UserInfo[ 'cover' ] ) ? '/'.$UserInfo[ 'cover' ] : '/assets/home/images/back.jpeg',
                    ];

                    Cookie::set( 'LoginUser', $cookie );
                    $this->success( '修改头像成功！' );
                    exit;
                }

                exit;
            }

            // 修改封面
            if ( $action == 'cover' ) {

                // 图片上传
                $imgURL = upload( 'cover' );

                if ( $imgURL === false ) {
                    $this->error( '修改封面失败！' );
                    exit;
                }

                // 组装数据
                $data = [
                    'id' => $LoginUser[ 'id' ],
                    'cover' => 'uploads/'.$imgURL
                ];

                // 修改数据库
                $resultCover = $this->UserModel->isUpdate()->save( $data );

                if ( $resultCover === false ) {

                    // 如果更新失败将上传的图片删除
                    @is_file( $data[ 'cover' ] ) && @unlink( $data[ 'cover' ] );

                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    // 修改成功后，删除原来的图片
                    $avatar = ltrim( $LoginUser[ 'cover' ], '/' );
                    @is_file( $avatar ) && @unlink( $avatar );

                    // 组装cookie的信息
                    $cookie = [
                        'id' => $LoginUser[ 'id' ],
                        'nickname' => $LoginUser[ 'nickname' ],
                        'vip' => $LoginUser[ 'vip' ],
                        'auth' => $LoginUser[ 'auth' ],
                        'avatar' => is_file( $UserInfo[ 'avatar' ] ) ? '/'.$UserInfo[ 'avatar' ] : '/assets/home/images/avatar.jpg',
                        'cover' => is_file( $data[ 'cover' ] ) ? '/'.$data[ 'cover' ] : '/assets/home/images/back.jpeg',
                    ];
                    Cookie::set( 'LoginUser', $cookie );

                    $this->success( '修改封面成功！' );
                    exit;
                }

                exit;
            }
            exit;
        }

        $UserInfo = $this->UserModel->where( [ 'id' => $LoginUser[ 'id' ] ] )->find();

        //查询地区表的省份数据
        $province = $this->RegionModel->where( [ 'grade' => 1 ] )->select();

        //判断当前这个用户是否有选择省份
        if ( empty( $UserInfo[ 'province' ] ) ) {

            $city = [];
        } else {

            $city = $this->RegionModel->where( [ 'parentid' => $UserInfo[ 'province' ] ] )->select();
        }

        //判断当前用户是否有选择城市
        if ( empty( $UserInfo[ 'city' ] ) ) {
            $district = [];
        } else {
            $district = $this->RegionModel->where( [ 'parentid' => $UserInfo[ 'city' ] ] )->select();
            // echo $this->RegionModel->getlastsql();
            // exit;
        }

        // var_dump( $district );
        // exit;
        // assign()渲染到前端, 个人信息，省份，市，区
        $this->assign( [
            'LoginUser' => $UserInfo,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ] );

        return  $this->fetch();
    }

    // 市

    public function area() {
        if ( $this->request->isPost() ) {
            $code = $this->request->param( 'code' );

            $city = $this->RegionModel->where( [ 'parentid' => $code ] )->select();

            //返回json数据
            return json( $city );
        }
    }

    // 区

    public function areadistrict() {
        if ( $this->request->isPost() ) {
            $code = $this->request->param( 'code' );

            $district = $this->RegionModel->where( [ 'parentid' => $code ] )->select();

            //返回json数据
            return json( $district );
        }
    }

    // 发送邮箱

    public function email() {
        if ( $this->request->isPost() ) {

            // 拿到邮箱
            $email = $this->request->param( 'email', '' );

            $success = [
                'result' => true,
                'msg' => '',
            ];

            // 组装邮箱
            if ( empty( $email ) ) {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = '邮箱不能为空！';
                exit;
            }

            // 邮箱加密
            $emails = md5( $email );

            // 组装信息
            $msg = "<a href='http://www.thinkphp.com/home/index/email?email=$emails'>点击免费邮箱验证</a>";

            // 调用公共函数库里面的发送方法
            $result = send( $email, $msg );

            if ( $result ) {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '邮箱发送成功！';
            } else {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = '邮箱发送失败！';
            }

            return json( $success );
        }
        exit;
    }

    // 检查输入框是否输入正确

    public function check() {
        $request = [
            'result' => false,
            'msg' => '',
        ];

        // 获取当前登录用户信息
        $LoginUser = Cookie::get( 'LoginUser' );

        // 获取用户其他信息
        $UserInfo = $this->UserModel->where( [ 'id' => $LoginUser[ 'id' ] ] )->find();

        if ( $this->request->isPost() ) {

            // 获取传来的的信息
            $params = $this->request->param();

            // 昵称操作
            if ( !empty( $params[ 'nickname' ] ) ) {
                // 获取输入的昵称
                $nickname = $params[ 'nickname' ];

                // 查询数据库是否有相同昵称的用户
                $res = $this->UserModel->where( [ 'nickname' => $nickname ] )->find();

                // 查询结果操作
                if ( $res == false ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '用户名不存在，可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else if ( $UserInfo[ 'nickname' ] == $nickname ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '用户名已存在，不可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

            // 旧密码操作
            if ( !empty( $params[ 'oldpass' ] ) ) {
                //获取输入的密码
                $oldpass = $params[ 'oldpass' ];

                // 密码加密
                $oldpass = md5( $oldpass.$UserInfo[ 'salt' ] );

                // 判断并操作
                if ( $oldpass == $UserInfo[ 'password' ] ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '密码正确！继续操作！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '密码错误！请重新输入！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

            // 新密码检查
            if ( !empty( $params[ 'newpass' ] ) ) {
                //获取输入的密码
                $newpass = $params[ 'newpass' ];

                // 密码加密
                $newpass = md5( $newpass.$UserInfo[ 'salt' ] );

                // 判断并操作
                if ( $newpass == $UserInfo[ 'password' ] ) {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '密码重复！请重新输入！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '密码不重复！继续操作！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

        }

    }

    // 我的帖子

    public function post() {
        // 获取当前登录用户信息
        $userId = $this->LoginUser[ 'id' ];

        // 查询全部帖子列表
        $postAll = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId ] )->order( 'createtime', 'desc' )->select();

        // 全部帖子数量
        $countAll = count( $postAll );

        // 十条
        $postAll = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId ] )->order( 'createtime', 'desc' )->paginate( 10 );

        // 获取分页显示
        $pageAllstr = $postAll->render();

        // 查询已结帖子
        $postClose = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId, 'accept' => [ 'exp', Db::raw( 'is not null' ) ] ] )->order( 'createtime', 'desc' )->select();

        // 已结帖子的数量
        $countClose = count( $postClose );

        $postClose = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId, 'accept' => [ 'exp', Db::raw( 'is not null' ) ] ] )->order( 'createtime', 'desc' )->paginate( 10 );

        // 获取分页显示
        $pageClosestr = $postClose->render();

        // 查询未结帖子
        $postOpen = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId, 'accept' => [ 'exp', Db::raw( 'is null' ) ] ] )->order( 'createtime', 'desc' )->select();

        // 未结数量
        $countOpen = count( $postOpen );

        $postOpen = $this->PostModel->with( [ 'cate', 'user' ] )->where( [ 'userid' => $userId, 'accept' => [ 'exp', Db::raw( 'is null' ) ] ] )->order( 'createtime', 'desc' )->paginate( 10 );

        // 获取分页显示
        $pageOpenstr = $postOpen->render();

        $this->assign( [
            'countAll' => $countAll,
            'postAll' => $postAll,
            'countClose' => $countClose,
            'postClose' => $postClose,
            'countOpen' => $countOpen,
            'postOpen' => $postOpen,
            'pageAllstr' => $pageAllstr,
            'pageClosestr' => $pageClosestr,
            'pageOpenstr' => $pageOpenstr
        ] );

        return $this->fetch();
    }

    // 我的收藏

    public function collect() {

        // 获取当前登录用户信息
        $userId = $this->LoginUser[ 'id' ];

        $postList = [];

        $collectList = $this->CollectModel->where( [ 'userid' => $userId ] )->select();

        foreach ( $collectList as $item ) {
            $postList[] = $this->PostModel->where( [ 'id' => $item[ 'postid' ] ] )->find();
        }

        $collectCount = count( $collectList );

        $this->assign( [
            'postList' => $postList,
            'collectCount' => $collectCount
        ] );
        return $this->fetch();
    }

    // 我的信息

    public function record() {
        // 获取当前登录用户信息
        $userId = $this->LoginUser[ 'id' ];

        $recordList = $this->RecordModel->where( [ 'userid' => $userId ] )->order( 'createtime', 'desc' )->paginate( 5 );

        $recordPage = $recordList->render();

        // 判断添加积分类型
        foreach ( $recordList as $item ) {
            switch( intval( $item[ 'state' ] ) ) {
                case 1:
                $item[ 'state' ] = '发布新帖';
                break;
                case 2:
                $item[ 'state' ] = '采纳评论';
                break;
                case 4:
                $item[ 'state' ] = '每日签到';
                break;
                default:
                break;
            }
        }

        $this->assign( [
            'recordList' => $recordList,
            'recordPage' => $recordPage
        ] );

        return $this->fetch();
    }

    // 删除信息

    public function delrecord() {
        // 提示信息
        $Tips = [
            'result' => false,
            'msg' => ''
        ];

        // 拿到传过来的数据
        $recordId = $this->request->param( 'recordid' );

        $recordRes = $this->RecordModel->where( [ 'id' => $recordId ] )->delete();

        if ( $recordRes === false ) {
            // 删除失败
            $Tips[ 'msg' ] = $this->RecordModel->getError();
        } else {
            // 删除成功
            $Tips[ 'result' ] = true;
            $Tips[ 'msg' ] = '删除成功！';
        }
        return $Tips;
    }

    // 全部信息删除

    public function delAll() {
        // 获取当前登录用户信息
        $userId = $this->LoginUser[ 'id' ];

        // 提示信息
        $Tips = [
            'result' => false,
            'msg' => ''
        ];

        $recordRes = $this->RecordModel->where( [ 'userid' => $userId ] )->delete();

        if ( $recordRes === false ) {
            // 删除失败
            $Tips[ 'msg' ] = $this->RecordModel->getError();
        } else {
            // 删除成功
            $Tips[ 'result' ] = true;
            $Tips[ 'msg' ] = '删除成功！';
        }
        return $Tips;
    }

}